package cn.myframe.config;

import java.util.Date;

import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * Spring动态周期定时任务<br>
 * 在不停应用的情况下更改任务执行周期 
 * 
 * @author ynz
 * @email ynz@myframe.cn
 * @date 2018年8月1日 上午8:10:45
 */
@Lazy(false)
@Component
@EnableScheduling
@Slf4j
public class SpringDynamicCronTask implements SchedulingConfigurer{

	private static String cron = "0 1 * * * ?";
	
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				// 任务逻辑
				log.debug("dynamicCronTask is running...");
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 任务触发，可修改任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
			}
		});
	}
}
